<template>
    <div class="container">
        <div class="content_wrapper">
            <div class="lyecs-form-table">
                <el-form v-if="!loading" ref="formRef" :rules="rules" :model="formState" label-width="auto">
                    <el-form-item prop="promotion_name" label="活动名称">
                        <el-input type="text" maxlength="60" v-model="formState.promotion_name" />
                    </el-form-item>
                    <el-form-item prop="product_time" label="活动时间">
                        <div>
                            <div>
                                <SelectTimeInterval
                                v-model:end-date="formState.end_time"
                                v-model:start-date="formState.start_time"
                                :clearable="false"
                                type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss"></SelectTimeInterval>
                            </div>
                            <div class="extra">只有当前时间介于起始日期和截止日期之间时，此活动才可以生效</div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="item" label="活动商品">
                        <DiscountForm v-model:skuIds="formState.item" :isMultiple="true" :isSku="true"></DiscountForm>
                    </el-form-item>
                    <el-form-item v-show="!props.isDialog" :wrapper-col="{ offset: 4, span: 16 }">
                        <el-button ref="submitBtn" class="form-submit-btn" type="primary" @click="onSubmit()">提交</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, shallowRef, onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { LimitdiscountFormState, discount_item } from "@/types/promotion/limitdiscount.d";
import { getLimitdiscount, updateLimitdiscount } from "@/api/promotion/limitdiscount";
import type { FormRules } from "element-plus";
import DiscountForm from "./src/DiscountForm.vue";
import { SelectTimeInterval } from "@/components/select";
import { getDays } from "@/utils/util";
import { formattedDate } from "@/utils/time";
const emit = defineEmits(["submitCallback", "update:confirmLoading", "close"]);
interface RuleForm {
    promotion_name: string;
    item: Array<discount_item>;
    product_time: string[];
}
const gifts = ref<any>([])
const validateTime = (rule: any, value: any, callback: any) => {
    if (!formState.value.start_time || !formState.value.end_time) {
        callback(new Error("活动日期不能为空"));
        return;
    } else {
        callback();
    }
};
const validateDiscount = (rule: any, value: any, callback: any) => {
    if(!formState.value.item){
        callback(new Error("活动商品不能为空"));
        return
    }else{
        callback();
    }
};
const rules = reactive<FormRules<RuleForm>>({
    promotion_name: [{ required: true, message: "请输入活动名称！", trigger: "blur" }],
    item: [{ required: true, validator: validateDiscount, trigger: "blur" }],
    product_time: [{ required: true, validator: validateTime, trigger: "blur" }],
});
const props = defineProps({
    id: {
        type: Number,
        default: 0,
    },
    promotion_type: {
        type: Number,
        default: 0,
    },
    act: {
        type: String,
        default: "",
    },
    isDialog: Boolean,
});
const loading = ref<boolean>(true);
const query = useRouter().currentRoute.value.query;
const action = ref<string>(props.isDialog ? props.act : String(query.act));
const id = ref<number>(props.isDialog ? props.id : Number(query.id));
const promotion_type = ref<number>(props.isDialog ? props.promotion_type : Number(query.coupon_type) || 0);
const operation = action.value === "add" ? "create" : "update";
const formRef = shallowRef();
const formState = ref<LimitdiscountFormState>({
    item:[]
});
onMounted(() => {
    if (action.value === "detail") {
        // 获取详情数据
        fetchProductActivity();
    } else {
        loading.value = false;
    }
});

const fetchProductActivity = async () => {
    try {
        const result = await getLimitdiscount(action.value, {
            discount_id: id.value,
            promotion_type: promotion_type.value,
        });
        console.log(result.item.discount_info)
        Object.assign(formState.value, result.item.discount_info);
    } catch (error: any) {
        message.error(error.message);
        emit("close");
    } finally {
        loading.value = false;
    }
};
// 表单通过验证后提交
const onSubmit = async () => {
    await formRef.value.validate();
    let discount_item:any[] = []
    formState.value.item.forEach((item:any) => {
        if(!item.value){
            message.error(`【${item.product.product_name}】: 请输入折扣值`);
            throw new Error();
        }
        if(item.discount_type == 1){
            if(item.value <= 0 || item.value > 9.9){
                message.error(`【${item.product.product_name}】: 请输入0.1-9.9之间折扣`);
                throw new Error();
            }
        }
        if(item.discount_type > 1){
            if(item.value <= 0 || item.value > Number(item.product_price)){
                message.error(`【${item.product.product_name}】: 请输入大于0并且小于商品原价的折扣`);
                throw new Error();
            }
        }
        // discount_item.push(item.sku_info)
    })
    // formState.value.item = discount_item
    console.log(formState.value)
    try {
        emit("update:confirmLoading", true);
        const result = await updateLimitdiscount(operation, { id: id.value, ...formState.value });
        emit("submitCallback", result);
        message.success(result.message);
    } catch (error: any) {
        message.error(error.message);
    } finally {
        emit("update:confirmLoading", false);
    }
};
// 表单提交
const onFormSubmit = () => {
    onSubmit();
};

defineExpose({ onFormSubmit });
</script>
